<?php

/**
 * Core phpFoX Language Class
 *
 * @author Raymond Benc aka natio <www.raybenc.com>
 * @package phpFoX_Language
 */
class Language
{
	/**
	 * Initiate language class
	 */
	function Language()
	{
		$this->loadLanguages();
	}

	function getDetails()
	{
		static $aCachedDetails;

		if ( $aCachedDetails )
		{
			return $aCachedDetails;
		}

		if ( !isset($this->aLanguage['id']) )
		{
			trigger_error("Cant find the language details", E_USER_ERROR);
		}

		$aCachedDetails = $this->aLanguage;

		return $aCachedDetails;
	}

	function getLangs()
	{
	 	static $sReturnId;

	 	if ( $sReturnId )
	 	{
	 	 	return $sReturnId;
	 	}

	 	if ( isset($_SESSION['temp_lang_id']) )
	 	{
	 		$sReturnId = $_SESSION['temp_lang_id'];
	 	}

		if ( $iLangId = App::getUser('lang_file') )
		{
			$oCache = &App::newObject("Cache");
			if ( Cache::isFile("phrases_". $iLangId .".php") )
			{
			 	$sReturnId = $iLangId;
			}
		}

		if ( !App::getUser('id') AND isset($_COOKIE['guest_lang']) )
		{
			$sReturnId = $_COOKIE['guest_lang'];
		}

		if ( isset($sReturnId) )
		{
			return $sReturnId;
		}

		$oDb = &Database::get();

		$aLanguages = $oDb->getRow("SELECT languageid AS id FROM ". App::getT('language') ."
			WHERE `default` = '1'");

		if ( !isset($aLanguages['id']) )
		{
			trigger_error("Cant load a default language package", E_USER_ERROR);
		}

		$_SESSION['temp_lang_id'] = $aLanguages['id'];

		$sReturnId = $aLanguages['id'];

		return $sReturnId;
	}

	function getLanguages()
	{
		$oDb = &Database::get();
		$oCache = &App::getCache();
		$oCache->setFile("language_listing.php");

		if ( !$oCache->isCached() )
		{
			$aItems = $oDb->getRows("SELECT languageid AS id, `title`, `userselect`, `languagecode`, `charset`, `direction`, `time`, `created`, `site`, `default` FROM
				". App::getT('language') ." ORDER BY `default` DESC");
			$oCache->save($aItems);
		}

		$aItems = $oCache->doRequire();

		return $aItems;
	}

	function formatOption($iId, $sType)
	{
		static $aItem;

		if ( isset($aItem[$iId]) )
		{
			return $aItem[$iId];
		}

		$oCache = &App::getCache();
		$oCache->setFile('option_'. $sType .'_'. $this->aLanguage['id'] .'.php');

		if ( !$oCache->isCached() )
		{
			$aItem = $this->getOptions($sType);
		}
		else
		{
			$aItem = $oCache->doRequire();
		}

		if ( isset($aItem[$iId]) )
		{
			return $aItem[$iId];
		}

		return '';
	}

	function getOptions($sName, $bGetDefault = false)
	{

		if ( $sName == 'day' )
		{
			$aItems = array();
			for($i = 1; $i <= 31; $i++)
			{
				$aItems[$i] = $i;
			}
			return $aItems;
		}

		if ( $sName == 'month' )
		{
			$aItems = array();
			for($i = 1; $i <= 12; $i++)
			{
				$iCachedVar = (($i < 10) ? '0' . $i : $i);
				$aItems[$iCachedVar] = $i;
			}
			return $aItems;
		}

		$oDb = &Database::get();
		$oCache = &App::getCache();
		$oCache->setFile('option_'. trim($oDb->escape($sName)) .'_'. $this->aLanguage['id'] .'.php');

		if ( !$oCache->isCached() )
		{
			$aItem = array();
			$aContents = $oDb->getRows("SELECT varid, text, selected FROM ". App::getT('language_options') ."
				WHERE varname = '". $oDb->escape($sName) ."' AND languageid = '". $this->aLanguage['id'] ."'");
			foreach($aContents as $sContent)
			{
				if ( !empty($sContent['selected']) )
				{
					$aItem['filter_selected_item'] = $sContent['varid'];
				}
				$aItem[$sContent['varid']] = $sContent['text'];
			}
			$oCache->save($aItem);
		}

		$aItems = array();
		$aCachedItems = $oCache->doRequire();

		if ( $sName == 'country' || $sName == 'event_items' || $sName == 'image_cat' || $sName == 'us_stat')
		{
			natcasesort($aCachedItems);
		}
		
		if (!$bGetDefault) 
		{
			unset($aCachedItems['filter_selected_item']);
		}
		
		foreach($aCachedItems as $sCachedId => $sCachedText)
		{
			$aItems[$sCachedId] = ucwords(strtolower($sCachedText));
		}

		if ( count($aItems) == 0 )
		{
			if (App::getParam('debug'))
			{
				trigger_error("Missing content item: ". $sName ."", E_USER_ERROR);
				return array();
			}
			return array();
		}

		return $aItems;
	}

	function getContent($sName, $bRedirect = false, $iLangId = 0)
	{
		$oDb = &Database::get();
		$oCache = &App::getCache();
		$oCache->setFile('content_'. trim($oDb->escape($sName)) .'_'. ($iLangId ? $iLangId : $this->aLanguage['id']) .'.php');

		if ( !$oCache->isCached() )
		{
			$aItem = $oDb->getRow("SELECT text FROM ". App::getT('language_phrase') ."
				WHERE `varname` = 'site_content_". trim($oDb->escape($sName)) ."' AND `languageid` = '". ($iLangId ? $iLangId : $this->aLanguage['id']) ."'");
			if ( !isset($aItem['text']) )
			{
				$aItem = $oDb->getRow("
					SELECT p.text 
					FROM ". App::getT('language_phrase') ." AS p
						LEFT JOIN " . App::getT('language') . " AS l
							ON l.default = '1'
					WHERE p.`varname` = 'site_content_". trim($oDb->escape($sName)) ."' AND p.languageid = l.languageid
				");
			}
			$oCache->save($aItem);
		}

		$aItem = $oCache->doRequire();

		if ( !isset($aItem['text']) )
		{
			if ( $bRedirect )
			{
				App::gotoUrl('public.error.404');
			}
			trigger_error("Missing content item: ". trim($sName) ."", E_USER_ERROR);
		}

		return $aItem['text'];
	}

	function removeCachedFiles()
	{
		$mDir = opendir(cachedDir);
		while ( $sFile = readdir($mDir) )
		{
			if ( substr($sFile, 0, 8) == 'phrases_'
				|| substr($sFile, 0, 10) == 'languages_'
				|| substr($sFile, 0, 8) == 'content_'
				|| substr($sFile, 0, 7) == 'option_'
			)
			{
				App::rmCache($sFile);
			}
		}
	}

	function setDefault($iId)
	{
		$oDb = &Database::get();

		$oDb->update(App::getT('language'), array('default' => ''), "languageid != '". $iId ."'");
		$oDb->update(App::getT('language'), array('default' => '1'), "languageid = '". $iId ."'");

		App::rmCache('language_listing.php');
		
		unset($_SESSION['temp_lang_id']);

		return true;
	}

	function deleteLanguage($iId)
	{
		$oDb = &Database::get();

		$oDb->_delete(App::getT('language'), "languageid = '". $iId ."'");
		$oDb->_delete(App::getT('language_options'), "languageid = '". $iId ."'");
		$oDb->_delete(App::getT('language_phrase'), "languageid = '". $iId ."'");

		App::rmCache('language_listing.php');

		$this->removeCachedFiles();

		$oDb->query("OPTIMIZE TABLE `". App::getT('language_options') ."`");
		$oDb->query("OPTIMIZE TABLE `". App::getT('language_phrase') ."`");

		return true;
	}

	function setGuestLang($iId)
	{
		$oDb = &Database::get();

		$aItem = $oDb->getField("SELECT COUNT(*) FROM ". App::getT('language') ." WHERE languageid = '". $oDb->escape($iId) ."'");

		if ( count($aItem) > 0 )
		{
			setcookie('guest_lang', $iId, time()+3600*24*365, '/');
			return true;
		}

		return false;
	}

    function getModuleFile($sName)
    {
    	static $aCachedPhrases;

    	if ( !isset($aCachedPhrases[$sName]) )
    	{
			if ( defined("benchMark") AND benchMark AND App::getParam('debug') )
			{
				$checkRequire = new BenchMark;
				$checkRequire->start();
			}
    		
    		$sCachedPhrase = "phrases_Mod_". $sName ."_". $this->aLanguage['id'] .".php";
    		$aCachedPhrases[$sName] = Cache::isRequire($sCachedPhrase);
    		
        	if ( defined("benchMark") AND benchMark AND App::getParam('debug') )
        	{
        		global $aLanguageGroups;
        		$aLanguageGroups[] = array
        		(
        			'name' => $sName,
        			'time' =>$checkRequire->finish2(),
        		);
        	}    		
    	}

    	return $aCachedPhrases[$sName];
    }

    function formatTranslate($sKey, $aParams = array())
    {
		$sCacheText = preg_replace( '/ +/', '-',preg_replace('/[^0-9a-z ]+/', '-', strtolower($sKey)));
		$sCacheText = 'Mod_Language.translate.'. $sCacheText .'';
		$sTempText = App::format($sCacheText, $aParams);
		if ( !empty($sTempText) || eregi('Missing:', $sTempText) )
		{
			if ( App::getParam('debug') && eregi('Missing:', $sTempText) )
			{
				return $sKey;
			}
			return $sTempText;
		}
		return $sKey;
    }

    /** Returns formatted mesage
     *
     * @param string $sKey message key
     * @param array  $aParam array of message parameters
     * @return string formateed message
     */
    function format($sKey, $aParams=array())
    {   	
    	static $aCacheDetails = "";

		if ( defined("benchMark") AND benchMark AND App::getParam('debug') )
		{
			$checkRequire = new BenchMark;
			$checkRequire->start();
		}    	
    	
    	$aGetModule = explode(".", $sKey);
    	if ( isset($aGetModule[0]) )
    	{
    		$sModule = str_replace("Mod_", "", $aGetModule[0]);
    	}

    	if ( isset($sModule) && !isset($aCacheDetails[$sModule]) && in_array($aGetModule[0], App::getParam('modules')) )
    	{
			$aCacheDetails[$sModule] = $this->getModuleFile($sModule);
    	}

        if ( defined("benchMark") AND benchMark AND App::getParam('debug') )
        {
        	global $aLanguageVars;
        	$aLanguageVars[] = array
        	(
        		'name' => $sKey,
        		'phrase' => (isset($aCacheDetails[$sModule][$sKey]) ? vsprintf($aCacheDetails[$sModule][$sKey], $aParams) : (isset($this->MSG[$sKey]) ? vsprintf($this->MSG[$sKey], $aParams) : '')),
        		'time' =>$checkRequire->finish2(),
        	);
        }     
        
		if ( App::getParam('debug.language.phrases') )
		{
    		echo "<!-- ". $sKey ." ";
    		if ( isset($aCacheDetails[$sModule][$sKey]) )
    		{
    			echo (App::getParam('debug.language.phrases') ? "{". vsprintf($aCacheDetails[$sModule][$sKey], $aParams) . "}" : vsprintf($aCacheDetails[$sModule][$sKey], $aParams));
    		}
    		else 
    		{
    			if (isset($this->MSG[$sKey]))
    			{
    				echo (App::getParam('debug.language.phrases') ? "{". vsprintf($this->MSG[$sKey], $aParams) . "}" : vsprintf($this->MSG[$sKey], $aParams));
    			}
    		}
    		echo " -->";
    	}	
    	
		if ( isset($aCacheDetails[$sModule][$sKey]) )
    	{
    		return (App::getParam('debug.language.phrases') ? "{". vsprintf($aCacheDetails[$sModule][$sKey], $aParams) . "}" : vsprintf($aCacheDetails[$sModule][$sKey], $aParams));
    	}

        if (!isset($this->MSG[$sKey]))
        {
        	if ( App::getParam('debug') )
        	{
            	return 'Missing: '. $sKey .'';
            }
            else
            {
            	return '';
            }
        }

        return (App::getParam('debug.language.phrases') ? "{". vsprintf($this->MSG[$sKey], $aParams) . "}" : vsprintf($this->MSG[$sKey], $aParams));
    }

    /** Does system contains given message
     *
     * @param string $sKey
     * @return bool
     */
    function hasMess($sKey)
    {
        return array_key_exists($sKey,$this->MSG);
    }

    /** Returns messages (or subset of messages)
     *
     * @param string $sStartWith return messages that start with given string
     * @return array messages ($key => $message)
     */
    function getMessages($sStartWith='')
    {
        if ($sStartWith)
        {
            $aRes = array();
            foreach($this->MSG as $k => $v)
            {
                if (strpos($k, $sStartWith)===0)
                {
                	$aRes[$k] = $v;
                }
            }

            if ( count($aRes) == 0 )
            {
    			$aGetModule = explode(".", $sStartWith);

    			if ( isset($aGetModule[0]) )
    			{
    				$sModule = str_replace("Mod_", "", $aGetModule[0]);
    			}

    			$aCacheDetails[$sModule] = $this->getModuleFile($sModule);

    			if ( isset($aCacheDetails[$sModule]) )
    			{
            		foreach($aCacheDetails[$sModule] as $k => $v)
            		{
                		if (strpos($k, $sStartWith)===0)
                		{
                			$aRes[$k] = $v;
                		}
            		}
    			}
            }

            return $aRes;
        }

        return $this->MSG;
    }

    function exportLanguagePackage($iId, $sProduct)
    {
    	$oDb = &Database::get();

		$aLanguage = $oDb->getRow("SELECT * FROM ". App::getT('language') ." WHERE languageid = '". $iId ."'");
		$i = 0;

		$aQuery = '$oDb->query("INSERT INTO ". App::getT(\'language\') ." SET ';
		foreach($aLanguage as $a => $b)
		{
			if ( $a != 'languageid' )
			{
				$i++;
				if ( $i != 1 )
				{
					$aQuery .= ", ";
				}
				$aQuery .= '`'. $a .'` = \''. ($b ? '". $oDb->escape(\''. str_replace("'", "\'", $b) .'\') ."' : ''. $b .'') .'\'';
			}
		}
		$aQuery .= '");' ."\n";
		$aQuery .= '$iCachedId = $oDb->getLastID();' . "\n";
		$aQuery .= "\n\n/* START THE IMPORT OF THE LANGUAGE PHRASES */\n\n";

		unset($a);
		unset($b);
		$aPhrases = $oDb->getRows("SELECT `varname`, `text`, `product`, `time`, `version`, `module`, `default`  FROM ". App::getT('language_phrase') ."
			WHERE languageid = '". $iId ."' AND product = '". $sProduct ."'");
		foreach($aPhrases as $aItems)
		{
			$i = 0;
			$aQuery .= '$oDb->query("INSERT INTO ". App::getT(\'language_phrase\') ." SET `languageid` = \'". $iCachedId ."\', ';
			foreach($aItems as $a => $b)
			{
				$i++;
				if ( $i != 1 )
				{
					$aQuery .= ", ";
				}
				$aQuery .= '`'. $a .'` = \''. ($b ? '". $oDb->escape(\''. (str_replace("'", "\'", $b)) .'\') ."' : ''. $b .'') .'\'';
			}
			$aQuery .= '");';
			$aQuery .= "\n";
		}

		$aQuery .= "\n\n/* END THE IMPORT OF THE LANGUAGE PHRASES */";
		$aQuery .= "\n\n/* START THE IMPORT OF THE LANGUAGE OPTIONS */\n\n";

		unset($a);
		unset($b);
		$aPhrases = $oDb->getRows("SELECT `varid`, `varname`, `text`, `product`, `time`, `default`  FROM ". App::getT('language_options') ."
			WHERE languageid = '". $iId ."' AND product = '". $sProduct ."'");
		foreach($aPhrases as $aItems)
		{
			$i = 0;
			$aQuery .= '$oDb->query("INSERT INTO ". App::getT(\'language_options\') ." SET `languageid` = \'". $iCachedId ."\', ';
			foreach($aItems as $a => $b)
			{
				$i++;
				if ( $i != 1 )
				{
					$aQuery .= ", ";
				}
				$aQuery .= '`'. $a .'` = \''. ($b ? '". $oDb->escape(\''. str_replace("'", "\'", $b) .'\') ."' : ''. $b .'') .'\'';
			}
			$aQuery .= '");';
			$aQuery .= "\n";
		}

		$aQuery .= "\n\n/* END THE IMPORT OF THE LANGUAGE OPTIONS */";

		@ob_clean();
		@ob_start();
		@ob_clean();
		header('Content-disposition: attachment; filename=phpfox-language_'. $aLanguage['languagecode'] .'.php');
		header('Content-type: unknown/unknown');
		print $aQuery;
		@ob_end_flush();
		exit;

		$sFileName = "phpfox-language_". $aLanguage['languagecode'] .".php";
		$sZipName = "phpfox-language_". $aLanguage['languagecode'] .".tar.gz";

		$oCache = &App::newObject("Cache");
		$oCache->setFile($sFileName);

		if ( $oCache->isCached() )
		{
			$oCache->rmFile($sFileName);
		}

		$oCache->createCached($aQuery);

		$zipline = "tar -czf ". cachedDir ."". $sZipName ." ". cachedDir ."". $oCache->fName($sFileName) ."";

		@shell_exec($zipline);

		if ( !file_exists(cachedDir . $sZipName) )
		{
			return false;
		}

		header("Location: ". cacheUrl ."". $sZipName ."");
    	exit;
    }

    function getCacheDetails($iId, $sName)
    {
    	$oDb = &Database::get();

		$aPhrases = $oDb->getRows("SELECT varname, text FROM ". App::getT('language_phrase') ."
			WHERE languageid = '". $iId ."' AND module = '". $sName ."'");

		$sContent = "";
		foreach($aPhrases as $aPhrase)
		{
			// $aPhrase['text'] = utf8_encode($aPhrase['text']);
			$sContent .= '\''. $aPhrase['varname'] .'\' => \''. str_replace("'", "\'", $aPhrase['text']) .'\',' ."";
		}

		return $sContent;
    }

    function getOptionVarId($sVarname)
    {
		$oDb = &Database::get();
		$iCnt = $oDb->getField("SELECT varid FROM ". App::getT('language_options') ."
			WHERE `varname` = '". $sVarname ."' AND `languageid` = '". $this->aLanguage['id'] ."' ORDER BY `varid` DESC");
		return ($iCnt + 1);
    }

	function loadLanguages()
	{
		$oDb = &Database::get();
		$oCache = &App::newObject("Cache");
		$bNoCachedRoutine = false;

		$sCacheId = strip_tags($this->getLangs());
		$sCachedFile = "languages_". $sCacheId .".php";
		$sCachedPhrase = "phrases_". $sCacheId .".php";

		if ( !Cache::isFile($sCachedFile) || !Cache::isFile($sCachedPhrase) )
		{
			$bNoCachedRoutine = true;
			$sLangDetails = "";
			$aLanguages = $oDb->getRows("SELECT languageid AS id, title, languagecode, charset, direction FROM ". App::getT('language') ."");
			foreach($aLanguages as $aLanguage)
			{
				$oCache->setFile("languages_". $aLanguage['id'] .".php");
				$sLangDetails .= "'id' => ". $aLanguage['id'] .",";
				$sLangDetails .= "'title' => '". $aLanguage['title'] ."',";
				$sLangDetails .= "'charset' => '". $aLanguage['charset'] ."',";
				$sLangDetails .= "'languagecode' => '". $aLanguage['languagecode'] ."',";
				$sLangDetails .= "'direction' => '". $aLanguage['direction'] ."',";
				$oCache->save($sLangDetails);
				$oCache->doRequire();

				$oCache->setFile("phrases_". $aLanguage['id'] .".php");
				$oCache->save($this->getCacheDetails($aLanguage['id'], ''));

				$aModules = App::getParam('modules');
				foreach($aModules as $aModule)
				{
					$oCache->setFile("phrases_". $aModule ."_". $aLanguage['id'] .".php");
					$oCache->save($this->getCacheDetails($aLanguage['id'], $aModule));
				}
			}
		}

		if ( $bNoCachedRoutine )
		{
			if ( isset($_COOKIE['guest_lang']) && !App::getUser('id') )
			{
				setcookie('guest_lang', '', -1, '/');
			}
		}

		$this->aLanguage = Cache::isRequire($sCachedFile);
		$this->MSG = Cache::isRequire($sCachedPhrase);
	}
}

?>